package com.demo.io.bytestream;

import org.junit.jupiter.api.Test;

import java.io.*;
import java.nio.charset.StandardCharsets;

/**
 * @author wangning
 * @date 2023/12/14 15:41
 * @description 输入流InputStream的使用，FileInputStream
 * 如果使用相对路径，可以考虑使用getClass().getResourceAsStream()方法来读取资源文件，这样路径就不再是相对路径，
 * 而是基于class文件的路径，这样在部署时更加稳定。
 * 另外，如果你的测试文件是放在项目的src/test/resources目录下，也可以使用getResourceAsStream()来读取，这样在运行测试时可以从资源目录中加载文件。
 */
public class InputStreamTest {

    @Test
    public void test() throws IOException {
        InputStream inputStream = getClass().getResourceAsStream("/file/test.txt");
        assert inputStream != null;
        System.out.println("inputStream = " + inputStream.read());

        InputStream inputStream2 = this.getClass().getResourceAsStream("/file/test.txt");
        InputStream inputStream3 = new FileInputStream("src/main/resources/file/test.txt");
        InputStream inputStream4 = new FileInputStream("src/main/java/com/demo/file/test.txt");
        InputStream inputStream5 = new FileInputStream("E:\\my-project\\workspace\\java-demo\\io\\src\\main\\java\\com\\demo\\file\\test.txt");
        InputStream inputStream6 = new FileInputStream(new File("src/main/resources/file/test.txt"));
        new BufferedInputStream(new FileInputStream(new File("src/main/resources/file/test.txt")));
        new BufferedInputStream(new FileInputStream(new File("./test.txt")));


    }

    @Test
    public void test1() {
        try {
            InputStream inputStream = new FileInputStream("src/main/resources/file/test.txt");
//            while (inputStream.available() > 0) {
//                int read = inputStream.read();
//                System.out.println(read);
//            }
            int len;
            byte[] bytes = new byte[1024];
            while ((len = inputStream.read(bytes)) != -1) {
                System.out.print(new String(bytes, 0, len, "UTF-8"));
            }
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * test1优化
     * 1. 使用try (InputStream inputStream = new FileInputStream(fileName))不用自己关闭资源
     * 2.打印日志清晰
     */
    @Test
    public void test2() {
        String fileName = "src/main/resources/file/test.txt";
        try (InputStream inputStream = new FileInputStream(fileName)) {
            int len;
            byte[] bytes = new byte[1024];
            while ((len = inputStream.read(bytes)) != -1) {
                System.out.print(new String(bytes, 0, len, StandardCharsets.UTF_8));
            }
        } catch (IOException e) {
            System.err.println("An I/O error occurred: " + e.getMessage());
        }
    }

}
